#!/bin/bash

set_usb_switch()
{
    gpio_chip=7
    gpio_num=24

    if [[ $1 == "OPEN" ]]
    then
        value=0
    elif [[ $1 == "DISCONNECT" ]]
    then
        value=1
    else
        return 0
    fi

    GPIO_BASE=(`ls /sys/class/gpio`)
    i=0
    while [ ${GPIO_BASE[${i}]} ]
    do
        GPIO_CHIP=${GPIO_BASE[${i}]#*gpiochip}

        GPIO_PATH="/sys/class/gpio/${GPIO_BASE[$i]}/device/gpiochip${gpio_chip}"
        if [ ! -e $GPIO_PATH ]
        then
            i=$((i+1))
            continue
        fi

        BASE=$(cat /sys/class/gpio/gpiochip${GPIO_CHIP}/base)
        CONTROL_GPIO=$((${BASE}+${gpio_num}))

        [ ! -d /sys/class/gpio/gpio${CONTROL_GPIO} ] && {
            echo $CONTROL_GPIO > /sys/class/gpio/export
        }

        echo "out" > /sys/class/gpio/gpio${CONTROL_GPIO}/direction
        echo ${value} > /sys/class/gpio/gpio${CONTROL_GPIO}/value

        echo $CONTROL_GPIO > /sys/class/gpio/unexport

        return 0;
    done
}


case "$1" in
START)
    set_usb_switch "OPEN"
    ;;
STOP)
    set_usb_switch "DISCONNECT"
    ;;
*)
    echo "invalid config $1" >&2
    exit 1
    ;;
esac
